package com.dataaccess.dataaccess.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.common.utils.ImageUtils;
import com.dataaccess.dataaccess.model.*;
import com.dataaccess.dataaccess.support.model.RespEntity;
import com.dataaccess.dataaccess.support.mybatisplus.QueryWrapper;
import com.dataaccess.dataaccess.web.mapper.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * @Author: YangYu
 * @ClassName: AsyncService
 * @Date: Created in 10:36 2021/12/8
 * @Description: 异步处理服务
 */
@Service
public class AsyncService extends BaseService {

    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private DeviceChannelMapper deviceChannelMapper;
    @Resource
    private WaterColumnBoxDataMapper waterColumnBoxDataMapper;
    @Resource
    private WaterColumnBoxDataLogMapper waterColumnBoxDataLogMapper;
    @Resource
    private PananSmockNumberMapper pananSmockNumberMapper;
    @Resource
    private GasFireExtinguishingDataMapper gasFireExtinguishingDataMapper;

    /**
     * @Author YangYu
     * @Description 异步更新海康梯控关门参数
     * @Date Created in 10:43 2021/12/8
     * @Param [jsonParam]
     */
    @Async
    public void updateHKCamera(JSONObject jsonParam) {
        JSONObject data = jsonParam.getJSONObject("data");
        JSONArray unattendedBaggage = data.getJSONArray("unattendedBaggage");
        JSONObject unattendedBaggageJson = (JSONObject) unattendedBaggage.get(0);
        JSONObject targetAttrs = unattendedBaggageJson.getJSONObject("targetAttrs");
        String cameraIndexCode = targetAttrs.getStr("cameraIndexCode");
        String deviceIndexCode = targetAttrs.getStr("deviceIndexCode");
        JSONObject jsonParamInfo = new JSONObject();
        jsonParamInfo.put("number", cameraIndexCode);
        jsonParamInfo.put("deviceCode", deviceIndexCode);
        fireFightingiot(jsonParamInfo, "firefightingiot", "updateHKCamera", "device");
    }

    /**
     * @Author YangYu
     * @Description 给安工院推送报警数据（加油站）
     * @Date Created in 14:02 2022/10/11
     * @Param [jsonParam]
     */
    @Async
    public RespEntity postGasStation(JSONObject jsonParam) throws IOException {
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness == null) {
            return RespEntity.fail("设备不存在");
        }
        Business business = businessMapper.selectById(deviceBusiness.getBusinessId());
        if (StrUtil.isBlank(business.getEnterpriseCode()) || !business.getEnterpriseCode().contains("@")) {
            return RespEntity.fail("企业信息不完善");
        }
        String[] enterpriseCode = business.getEnterpriseCode().split("@");
        //推送数据
        JSONObject postData = new JSONObject();
        if (jsonParam.getStr("content").equals("区域入侵")) {
            postData.put("alarmType", "2");
        } else if (jsonParam.getStr("content").equals("离岗检测")) {
            postData.put("alarmType", "3");
        } else if (jsonParam.getStr("content").equals("打电话检测")) {
            postData.put("alarmType", "6");
        } else if (jsonParam.getStr("content").equals("吸烟检测")) {
            postData.put("alarmType", "7");
        } else if (jsonParam.getStr("content").equals("烟火检测")) {
            postData.put("alarmType", "10");
        } else {
            return RespEntity.fail("报警类型不匹配");
        }
        postData.put("deviceCode", enterpriseCode[1]);
        postData.put("alarmId", UUID.randomUUID().toString());
        postData.put("alarmDate", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        postData.put("alarmAction", "start");
        String[] areaName = business.getAreaName().split(",");
        //base64图片转文件
        MultipartFile file = ImageUtils.base64ToMultipartFile("data:image/jpeg;base64," + jsonParam.getStr("image"));
        if (areaName[1].equals("东营市")) {
            postData.put("channelCode", enterpriseCode[1].substring(0, 9) + "013200000" + jsonParam.getStr("ChannelId"));
            if (areaName[2].equals("东营区")) {
                postData.put("areaCode", "370502");
            } else if (areaName[2].equals("河口区")) {
                postData.put("areaCode", "370503");
            } else if (areaName[2].equals("垦利县")) {
                postData.put("areaCode", "370505");
            } else if (areaName[2].equals("利津县")) {
                postData.put("areaCode", "370522");
            } else if (areaName[2].equals("广饶县")) {
                postData.put("areaCode", "370523");
            } else if (areaName[2].equals("东营经济技术开发区")) {
                postData.put("areaCode", "370571");
            } else if (areaName[2].equals("东营港经济开发区")) {
                postData.put("areaCode", "370572");
            } else if (areaName[2].equals("黄河三角洲农业高新技术产业示范区")) {
                postData.put("areaCode", "370590");
            }
            postData.put("companyName", business.getName());
            postData.put("creditCode", enterpriseCode[0]);
            restDY(postData, "whpjg", "videoDeviceAlarm", "anGongYuan", "", file);
            //TODO 目前报警接着消除后期可能会改
            postData.put("alarmAction", "stop");
            restDY(postData, "whpjg", "videoDeviceAlarm", "anGongYuan", "", file);
        } else {
            List<DeviceChannel> deviceChannelList = deviceChannelMapper.selectList(new QueryWrapper<DeviceChannel>().eq("device_id", deviceBusiness.getId()));
            if (deviceChannelList.size() == 0) {
                return RespEntity.fail("通道不完善");
            }
            for (DeviceChannel deviceChannel : deviceChannelList) {
                if (deviceChannel.getChannel().equals(jsonParam.getStr("ChannelId"))) {
                    postData.put("channelCode", deviceChannel.getChannelCode());
                    break;
                }
            }
            if (postData.containsKey("channelCode")) {
                return RespEntity.fail("没有匹配的通道");
            }
            restAGYAlarm(postData, "agy", "alarm", "anGongYuan", "", file);
            //TODO 目前报警接着消除后期可能会改
            postData.put("alarmAction", "stop");
            if (areaName[1].equals("济南市")) {
                postData.put("areaCode", "003701");
            } else if (areaName[1].equals("青岛市")) {
                postData.put("areaCode", "003702");
            } else if (areaName[1].equals("淄博市")) {
                postData.put("areaCode", "003703");
            } else if (areaName[1].equals("枣庄市")) {
                postData.put("areaCode", "003704");
            } else if (areaName[1].equals("烟台市")) {
                postData.put("areaCode", "003706");
            } else if (areaName[1].equals("潍坊市")) {
                postData.put("areaCode", "003707");
            } else if (areaName[1].equals("济宁市")) {
                postData.put("areaCode", "003708");
            } else if (areaName[1].equals("泰安市")) {
                postData.put("areaCode", "003709");
            } else if (areaName[1].equals("威海市")) {
                postData.put("areaCode", "003710");
            } else if (areaName[1].equals("日照市")) {
                postData.put("areaCode", "003711");
            } else if (areaName[1].equals("临沂市")) {
                postData.put("areaCode", "003713");
            } else if (areaName[1].equals("德州市")) {
                postData.put("areaCode", "003714");
            } else if (areaName[1].equals("聊城市")) {
                postData.put("areaCode", "003715");
            } else if (areaName[1].equals("滨州市")) {
                postData.put("areaCode", "003716");
            } else if (areaName[1].equals("菏泽市")) {
                postData.put("areaCode", "003717");
            }
            postData.put("alarmAction", "stop");
            postData.put("companyName", business.getName());
            postData.put("creditCode", enterpriseCode[0]);
            restAGYStopAlarm(postData, "whpjg", "videoDeviceAlarm", "anGongYuan", "", file);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 异步更新设备状态
     * @Date Created in 9:56 2022/10/27
     * @Param [jsonParam]
     */
    @Async
    public void updateDeviceCurrentState(JSONObject jsonParam) {
        System.out.println(jsonParam);
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("number", jsonParam.getStr("number"));
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setNormalUpdateTime(DateUtil.now());
        deviceBusiness.setCurrentstate(jsonParam.getStr("state"));
        deviceBusinessMapper.update(deviceBusiness, updateWrapper);
    }

    /**
     * @Author YangYu
     * @Description 异步更新维保部件设备状态
     * @Date Created in 9:56 2022/10/27
     * @Param [jsonParam]
     */
    @Async
    public void updateFireFightingPartsState(String number) {
        deviceBusinessMapper.updateFireFightingPartsState(number);
    }


    /**
     * @Author YangYu
     * @Description 异步更新水柱箱体数据
     * @Date Created in 9:56 2022/10/27
     * @Param [jsonParam]
     */
    @Async
    public void updateWaterColumnBoxData(JSONObject jsonParam) {
        WaterColumnBoxData waterColumnBoxData = new WaterColumnBoxData();
        waterColumnBoxData.setNumber(jsonParam.getStr("number"));
        waterColumnBoxData.setLrv(jsonParam.getDouble("lrv"));
        waterColumnBoxData.setUpperRangeLimit(jsonParam.getDouble("upperRangeLimit"));
        waterColumnBoxData.setPercentage(jsonParam.getStr("percentage"));
        waterColumnBoxData.setUpperLimitAlarmSettingValues(jsonParam.getDouble("upperLimitAlarmSettingValues"));
        waterColumnBoxData.setUpperLimitAlarmSettingValue(jsonParam.getDouble("upperLimitAlarmSettingValue"));
        waterColumnBoxData.setLowerLimitAlarmSetPoint(jsonParam.getDouble("lowerLimitAlarmSetPoint"));
        waterColumnBoxData.setLowerLimitAlarmSetPoints(jsonParam.getDouble("lowerLimitAlarmSetPoints"));
        waterColumnBoxData.setStartValue(jsonParam.getDouble("startValue"));
        waterColumnBoxData.setStopValue(jsonParam.getDouble("stopValue"));
        waterColumnBoxData.setManualAutomaticState(jsonParam.getInt("manualAutomaticState"));
        waterColumnBoxData.setSignalPercentage(jsonParam.getStr("signalPercentage"));
        waterColumnBoxDataMapper.delete(new QueryWrapper<WaterColumnBoxData>().eq("number", jsonParam.getStr("number")));
        waterColumnBoxDataMapper.insert(waterColumnBoxData);
        //更新下发指令的设备ID
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("number", jsonParam.getStr("number"));
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setDownDevId(jsonParam.getStr("deviceId"));
        deviceBusinessMapper.update(deviceBusiness, updateWrapper);
        WaterColumnBoxDataLog waterColumnBoxDataLog = new WaterColumnBoxDataLog();
        waterColumnBoxDataLog.setNumber(jsonParam.getStr("number"));
        waterColumnBoxDataLog.setWaterLevel(jsonParam.getStr("waterLevel"));
        waterColumnBoxDataLog.setDateTime(DateUtil.now());
        waterColumnBoxDataLogMapper.insert(waterColumnBoxDataLog);
    }

    /**
     * @Author YangYu
     * @Description 异步无限仪表数据（经典云@正润）
     * @Date Created in 9:56 2022/10/27
     * @Param [jsonParam]
     */
    @Async
    public void updateWirelessInstrumentData(JSONObject jsonParam) {
        WaterColumnBoxData waterColumnBoxData = new WaterColumnBoxData();
        waterColumnBoxData.setNumber(jsonParam.getStr("number"));
        waterColumnBoxData.setVersion(jsonParam.getStr("version"));
        waterColumnBoxData.setElectricity(jsonParam.getStr("electricity"));
        waterColumnBoxData.setSignalPercentage(jsonParam.getStr("signalPercentage"));
        waterColumnBoxData.setUpperLimitAlarmSettingValue(jsonParam.getDouble("upperLimitAlarmSettingValue"));
        waterColumnBoxData.setLowerLimitAlarmSetPoint(jsonParam.getDouble("lowerLimitAlarmSetPoint"));
        waterColumnBoxDataMapper.delete(new QueryWrapper<WaterColumnBoxData>().eq("number", jsonParam.getStr("number")));
        waterColumnBoxDataMapper.insert(waterColumnBoxData);
        //更新下发指令的设备ID
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("number", jsonParam.getStr("number"));
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setDownDevId(jsonParam.getStr("deviceId"));
        deviceBusiness.setNormalUpdateTime(DateUtil.now());
        deviceBusiness.setWaterValue(jsonParam.getStr("waterLevel"));
        deviceBusiness.setUnit(jsonParam.getStr("unit"));
        deviceBusinessMapper.update(deviceBusiness, updateWrapper);
        WaterColumnBoxDataLog waterColumnBoxDataLog = new WaterColumnBoxDataLog();
        waterColumnBoxDataLog.setNumber(jsonParam.getStr("number"));
        waterColumnBoxDataLog.setWaterLevel(jsonParam.getStr("waterLevel"));
        waterColumnBoxDataLog.setDateTime(DateUtil.now());
        waterColumnBoxDataLogMapper.insert(waterColumnBoxDataLog);
    }

    /**
     * @Author YangYu
     * @Description 更新物联网卡号
     * @Date Created in 13:11 2023/9/7
     * @Param [jsonParam]
     */

    @Async
    public void update_ICCID(JSONObject jsonParam) {
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("number", jsonParam.getStr("number"));
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setInternetofthingsCardnum(jsonParam.getStr("iccid"));
        this.deviceBusinessMapper.update(deviceBusiness, updateWrapper);
        Integer count = this.pananSmockNumberMapper.selectCount((new QueryWrapper()).eq("device_number", jsonParam.getStr("number")));
        if (count <= 0) {
            PananSmockNumber pananSmockNumber = new PananSmockNumber();
            pananSmockNumber.put("id", UUID.randomUUID().toString());
            pananSmockNumber.put("ieimNumber", jsonParam.getStr("number"));
            pananSmockNumber.put("iotNumber", jsonParam.getStr("iccid"));
            this.pananSmockNumberMapper.insert(pananSmockNumber);
        }

    }

    /**
     * @Author YangYu
     * @Description 更新用户传输设备部件为在线状态
     * @Date Created in 13:11 2023/9/7
     * @Param [jsonParam]
     */

    @Async
    public void update_user_transmission_state(JSONObject jsonParam) {
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper();
        updateWrapper.like("number", jsonParam.getStr("number"));
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setCurrentstate("1");
        deviceBusiness.setNormalUpdateTime(jsonParam.getStr("time"));
        this.deviceBusinessMapper.update(deviceBusiness, updateWrapper);
    }

    /**
     * @Author YangYu
     * @Description 异步维护水设备最新一包数据
     * @Date Created in 9:56 2022/10/27
     * @Param [jsonParam]
     */
    @Async
    public void updateWaterDeviceValue(JSONObject jsonParam) {
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("number", jsonParam.getStr("number"));
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setWaterValue(jsonParam.getStr("value"));
        deviceBusinessMapper.update(deviceBusiness, updateWrapper);
    }

    /**
     * @Author YangYu
     * @Description 气体灭火数据
     * @Date Created in 9:56 2022/10/27
     * @Param [jsonParam]
     */
    @Async
    public void updateGasFireExtinguishingData(JSONObject jsonParam) {
        //先删除
        gasFireExtinguishingDataMapper.delete(new QueryWrapper<GasFireExtinguishingData>().eq("number", jsonParam.getStr("number")));

        GasFireExtinguishingData gasFireExtinguishingData = new GasFireExtinguishingData();
        gasFireExtinguishingData.setNumber(jsonParam.getStr("number"));
        gasFireExtinguishingData.setTemperature(jsonParam.getDouble("temperature"));
        gasFireExtinguishingData.setFireExtinguishingDeviceState(jsonParam.getInt("extinguishingDeviceState"));
        gasFireExtinguishingData.setTemperatureState(jsonParam.getInt("temperatureState"));
        gasFireExtinguishingData.setSmokeState(jsonParam.getInt("smokeState"));
        gasFireExtinguishingDataMapper.insert(gasFireExtinguishingData);
    }

    /**
     * @Author YangYu
     * @Description 更新电信AEP下发指令ID
     * @Date Created in 13:11 2023/9/7
     * @Param [jsonParam]
     */

    @Async
    public void updateDeviceTermId(JSONObject jsonParam) {
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper();
        updateWrapper.like("number", jsonParam.getStr("number"));
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setTermId(jsonParam.getStr("deviceId"));
        this.deviceBusinessMapper.update(deviceBusiness, updateWrapper);
    }

    /**
     * @Author YangYu
     * @Description 更新tcp_server下发指令ID
     * @Date Created in 13:11 2023/9/7
     * @Param [jsonParam]
     */

    @Async
    public void updateDeviceDownDevId(JSONObject jsonParam) {
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper();
        updateWrapper.like("number", jsonParam.getStr("number"));
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setDownDevId(jsonParam.getStr("deviceId"));
        this.deviceBusinessMapper.update(deviceBusiness, updateWrapper);
    }
}
